package com.huidian.gitbatchprocessing.ui.service.impl;

import com.huidian.gitbatchprocessing.git.entity.MyMergeResult;
import com.huidian.gitbatchprocessing.git.util.GitUtil;
import com.huidian.gitbatchprocessing.ui.enums.BranchOperateEnum;
import com.huidian.gitbatchprocessing.ui.service.AbstractBranchOperate;
import com.huidian.gitbatchprocessing.ui.service.dto.BaseBranchDto;
import com.huidian.gitbatchprocessing.ui.service.dto.MergeBranchDto;
import com.intellij.openapi.util.text.StringUtil;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.util.StringUtils;

import java.util.List;

/**
 * 创建分支操作
 *
 * @author zxb
 * @date 2021/6/18
 */
public class MergeBranchOperateImpl extends AbstractBranchOperate {

    @Override
    public Byte getKey() {
        return BranchOperateEnum.MERGE_BRANCH.getKey();
    }

    @Override
    public String execute(BaseBranchDto baseBranchDto, Repository repository) throws Exception {
        MergeBranchDto mergeBranchDto = (MergeBranchDto) baseBranchDto;
        String mergeBranchSourceName = mergeBranchDto.getSourceBranchName();
        String mergeBranchTargetName = mergeBranchDto.getTargetBranchName();
        if (StringUtil.isEmpty(mergeBranchSourceName)) {
            throw new RuntimeException("源分支名不能为空！");
        }
        if (StringUtil.isEmpty(mergeBranchTargetName)) {
            throw new RuntimeException("目标分支名不能为空！");
        }
        Git git = new Git(repository);
        MyMergeResult merge = GitUtil.merge(git, mergeBranchSourceName, mergeBranchTargetName);
        if (merge.isSuccess()) {
            return merge.getMsg();
        } else {
            List<String> conflictNameList = merge.getConflictNameList();
            return merge.getMsg() + "\n冲突文件如下：\n" + StringUtils.join(conflictNameList, "\n");
        }
    }
}
